package com.zf.shuashua.utils;

import com.zf.shuashua.BuildConfig;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;

public class RunLinuxCommand {
    public static boolean isRooted() {
        if (BuildConfig.ENABLE_DEBUG) {
            return false;
        }
        //检测是否ROOT过
        DataInputStream stream;
        boolean flag = false;
        try {
            stream = terminal("ls /data/");
            //目录哪都行，不一定要需要ROOT权限的
            if (stream.readLine() != null) flag = true;
            //根据是否有返回来判断是否有root权限
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return flag;
    }

    public static boolean isDeviceRooted() {
        if (BuildConfig.ENABLE_DEBUG) {
            return false;
        }
        String su = "su";
        String[] locations = {"/system/bin/", "/system/xbin/", "/sbin/", "/system/sd/xbin/",
                "/system/bin/failsafe/", "/data/local/xbin/", "/data/local/bin/", "/data/local/",
                "/system/sbin/", "/usr/bin/", "/vendor/bin/"};
        for (String location : locations) {
            if (new File(location + su).exists()) {
                return true;
            }
        }
        return false;
    }

    private static DataInputStream terminal(String command) throws Exception {
        Process process = Runtime.getRuntime().exec("su");
        //执行到这，Superuser会跳出来，选择是否允许获取最高权限
        OutputStream outstream = process.getOutputStream();
        DataOutputStream DOPS = new DataOutputStream(outstream);
        InputStream instream = process.getInputStream();
        DataInputStream DIPS = new DataInputStream(instream);
        String temp = command + "\n";
        //加回车
        DOPS.writeBytes(temp);
        //执行
        DOPS.flush();
        //刷新，确保都发送到outputstream
        DOPS.writeBytes("exit\n");
        //退出
        DOPS.flush();
        process.waitFor();
        return DIPS;
    }
}
